# encoding: utf-8
# 项目名称： day02
# @File  : task.py
# @Author: sun hao
# @Desc : 
# @Date  :   19:58 2024/10/08

import json
from django import forms
from django.contrib.admin.templatetags.admin_list import result_list
from django.shortcuts import HttpResponse, render, redirect
from django.http import JsonResponse
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.core.validators import RegexValidator
from django.core.exceptions import ValidationError
from django.views.decorators.csrf import csrf_exempt
from app01.utils.layUI import LayUiModelForm
from app01 import models


class TaskModelForm(LayUiModelForm):
    class Meta:
        model = models.Task
        fields = '__all__'
        widgets = {
            'information': forms.Textarea(attrs={"class": "layui-textarea"})
        }

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['information'].widget.attrs['class'] = "layui-textarea"


def task_list(request):
    """
        任务列表
    """
    form = TaskModelForm()

    # 获取并验证分页参数
    try:
        page = max(1, int(request.GET.get('page', 1)))
    except ValueError:
        page = 1

    try:
        limit = max(1, min(100, int(request.GET.get('limit', 10))))
    except ValueError:
        limit = 10

    # 查询数据并排序
    queryset = models.Task.objects.all().order_by('-id')

    # 使用Django的Paginator进行分页
    paginator = Paginator(queryset, limit)
    try:
        data_list = paginator.page(page)
    except PageNotAnInteger:
        data_list = paginator.page(1)
    except EmptyPage:
        data_list = paginator.page(paginator.num_pages)

    context = {
        'form': form,
        'data_list': data_list,
        'totals': paginator.count,
        'current_page': data_list.number,
        'page_size': limit,
        'total_pages': paginator.num_pages,
    }
    return render(request, 'task/list.html', context)





@csrf_exempt
def task_add(request):
    """
        新建任务,前端通过ajax来交互数据
    """
    print(request.GET)
    print(request.POST)
    form = TaskModelForm(request.POST)
    if form.is_valid():
        # 验证成功
        form.save()
        data_dict = {"status": True, "code": "200"}
        return JsonResponse(data_dict)
    # form.errors
    data_dict = {"status": False, "code": "500", "error": form.errors}
    return JsonResponse(data_dict)


@csrf_exempt
def task_ajax(request):
    """
        使用 csrf_exempt 免除接口post提交时，会提示403的控制
    """
    print(request.GET)
    print(request.POST)
    # 方式1
    data_dict = {"status": True, "data_list": [1, 2, 3, 4, 5, 6, 7]}
    # result_info = json.dumps(data_dict)
    # return HttpResponse(result_info)
    # 方式2 django自带的 简写 JsonResponse
    return JsonResponse(data_dict)
    # return HttpResponse('请求成功')
